#include "httplib/httplib.h"
#include "searcher.hpp"
#include <iostream>
#include <cstring>
#include <string>
#include "log.hpp"

const std::string info_file = "./data/output/raw.txt";
const std::string root_path = "./wwwroot";

extern Log lg;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " port[1024+]\n";
        return 1;
    }
    lg.change_record_op(diverse_file);
    ns_searcher::searcher* boost_searcher = ns_searcher::searcher::get_instance();
    boost_searcher->init_searcher();

    std::thread forward_build(&ns_index::index::build_forward_index, boost_searcher->data_index);
    std::thread inverted_build(&ns_index::index::build_inverted_index, boost_searcher->data_index);

    lg(Info, "build index success!");

    httplib::Server svr;
    svr.set_base_dir(root_path);
    svr.Get("/s", [&boost_searcher](const httplib::Request& req, httplib::Response& rsp)
        {
            if (!req.has_param("word"))
            {
                rsp.set_content("必须输入关键字", "text/plain; charset=utf-8");
                return;
            }
            std::string query = req.get_param_value("word");
            // std::cout << "用户的搜索关键字：" << query << std::endl;
            lg(Info, "用户搜索关键字：%s", query.c_str());
            std::string json_str = boost_searcher->search(query);
            rsp.set_content(json_str, "application/json"); });

    int port = atoi(argv[1]);
    svr.listen("0.0.0.0", port);
    return 0;
}